package com.pj.lib.auraClient.API;

import java.io.IOException;

import android.util.Log;

import com.pj.lib.aura.connection.Result;
import com.pj.lib.aura.protocol.AuraProtocolMapKeys;
import com.pj.lib.auraClient.Aura;
import com.pj.lib.auraClient.AuraComponent;

import com.pj.lib.auraClient.AuraService.ConnectionStatus;
import com.pj.lib.auraClient.interfaces.OnServiceConnection;
import com.pj.lib.auraClient.interfaces.OnUserAPI;

public class AuraUser extends AuraComponent{
	private static final String TAG = "AuraUser";
	private Boolean waiting = false;
	
	private Result result;
	
	public AuraUser(Aura aura) {
		super(aura);
		
		if(getAura().isServiceBounded()) {
			getAura().getService().addOnUserApiListener(new UserAPIHandler());
		} else {
			getAura().addOnServiceConnectionListener(new OnServiceConnection() {
				
				@Override
				public void serviceConnection(Boolean isConnected) {
					if(isConnected) {
						getAura().getService().addOnUserApiListener(new UserAPIHandler());
					}
				}
			});
		}
	}

	synchronized private void resume() {
		notify();
	}
	synchronized private void pause() throws InterruptedException {
		waiting = true;
		wait();
	}
	/*synchronized public int getSome() {
		getAura().getService().sendSome();
		wait();
		
	}*/
	public Result login(String username, String password) {
		try {
			getAura().getService().getConnectionThread().handleSendLogin(username, password);
			
			pause();
			
			return result;
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		} catch (InterruptedException e) {
			Log.e(TAG, e.getMessage());
		}
		return null;
	}
	
	public Result createAccount(String username, String password) {
		try {
			getAura().getService().getConnectionThread().handleSendCreateAccount(username, password);
			
			pause();
			
			return result;
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		} catch (InterruptedException e) {
			Log.e(TAG, e.getMessage());
		}
		return null;
	}
	
	
	private class UserAPIHandler implements OnUserAPI {

		
		@Override
		public void loginResult(Boolean result, String description, Integer userId) {
			if(waiting) {
				AuraUser.this.result = new Result(result, description);
				AuraUser.this.result.addValue(AuraProtocolMapKeys.USER_ID_KEY, userId);
				resume();
			}
		}
		
		@Override
		public void connectionStatus(ConnectionStatus status) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void createAccountResult(Boolean result, String description,
				Integer userId) {
			if(waiting) {
				AuraUser.this.result = new Result(result, description);
				AuraUser.this.result.addValue(AuraProtocolMapKeys.USER_ID_KEY, userId);
				resume();
			}
			
		}
	}


	
}
